﻿
var Tippelde = window.Tippelde || {};

Tippelde.TeamSelector = function (urlParam, selector) {
    $.widget("ui.combobox", {
        _create: function () {
            var self = this,
                select = this.element.hide(),
                selected = select.children(":selected"),
                value = selected.text();
            var hiddenInput = select.parent().find('input[type="hidden"]');

            var input = this.input = $("<input>").insertAfter(select).val(value).attr('placeholder', 'Kezdd gépelni a csapat nevét').autocomplete({
                delay: 0,
                minLength: 1,
                source: function (request, response) {
                    $.ajax({
                        url: urlParam,
                        type: "GET",
                        dataType: "json",
                        data: {
                            q: request.term
                        },
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.Name + " (" + item.ShortName + ")",
                                    value: item.Id
                                }
                            }));
                        }
                    })
                },
                select: function (event, ui) {
                    hiddenInput.val(ui.item.value);
                    input.val(ui.item.label);
                    ui.item.value = ui.item.label;
                },
                focus: function (event, ui) {
                    preventDefault();
                },

            }).addClass("ui-widget ui-widget-content form-control");
        },

        destroy: function () {
            this.input.remove();
            this.button.remove();
            this.element.show();
            $.Widget.prototype.destroy.call(this);
        }
    });

    $(selector).combobox({
        source: urlParam,
        dataType: "json",
        minLength: 2,
        select: function (event, ui) {
            console.log(ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value);
        }

    });

}